package com.feige.security;


import com.feige.constant.Constants;
import com.feige.entity.SecurityUser;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import com.feige.utils.http.ServletUtils;
import com.feige.utils.string.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Service("ss")
public class PreAuthService {

    @Resource
    private RedisUtils redisUtils;

    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission) {

        return permissions.contains(ALL_PERMISSION) || permissions.contains(permission.trim());
    }


    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPerm(String permission) {
        if (StringUtils.isEmpty(permission))
        {
            return false;
        }
        HttpServletRequest request = ServletUtils.getRequest();
        String token = request.getHeader(Constants.TOKEN_KEY);
        String username = JwtUtils.getUsernameAndNumFromToken(token);
        SecurityUser securityUser = (SecurityUser) redisUtils.get(Constants.LOGIN_USER_KEY + username);
        if (StringUtils.isNull(securityUser) || CollectionUtils.isEmpty(securityUser.getPermissions()))
        {
            return false;
        }
        return hasPermissions(securityUser.getPermissions(), permission);
    }
}
